var recordsUrl 	= "map/records";
var addUrl 		= "map/create";
var editUrl 	= "map/update";
var deleteUrl 	= "map/delete";
var reorderUrl 	= "map/wms/reorder";

var gridCols = {set:false},
      	gridMultiSelect = 1,
      	selArr = [];      
      	
      	emp.$(function() {
//      		var lastsel = -1;
      		emp.$("#wms-grid").jqGrid({
      			url:recordsUrl,
      			index:'urlId',
      			datatype: 'json',
      			mtype: 'GET',
      			colNames:['id', 'Name', 'Url', 'Type', 'Active'],
      			colModel:[
      			          {name:'urlId', index:'urlId', width:200, editable:true,  editrules: {required:true}, editoptions:{size:10},  hidden:true, key:true},
      			          {name: 'name', index: 'name', width:130, editable: true, editrules: {required:true}, editoptions:{size: 50}, cellattr: function(rowId, tv, rawObject, cm, rdata) {
      			        	  return 'style="white-space: normal;"';      			        	  
      			          }},
      			          {name: 'serverUrl', index: 'serverUrl', width: 200, editable: true, editrules: {required: true}, editoptions: {size: 55}, cellattr: function(rowId, tv, rawObject, cm, rdata) {
      			        	  return 'style="white-space: normal;"';      			        	  
      			          }},
      			          {name: 'type',   index: 'type',   width: 100, edittype:"select",   editable: true, formatter: 'select',   editoptions: {value:"WMS-URL:WMS Server;WW-Elev:World Wind Elevation"}, align:"center" },
      			          {name: 'active', index: 'active', width: 50,  edittype:"checkbox", editable: true, formatter: 'checkbox', editoptions: {value:"True:False"}, formatoptions:{disabled : false},    align:"center",classes:'isActive' }
      			          
      			],
      			postData: {},
      			rowNum:10,
      			rowList:[10,20,40,60],
      			height: 'auto',
      			autowidth: true,
      			width: 'auto',
      			rownumbers: true,
      			pager: '#pager1',
      			sortname: 'name',
      			gridview: true,
      			viewrecords: true,
      			sortorder: "asc",
      			sortable: function (permutation) {
      				alert ('permutation=' + permutation.join(','));
      			},
      			caption:"WMS URL Configuration",
      			emptyrecords: "Empty records",
      			loadonce: false,
      			shrinkToFit: true,
      			autowidth: true,
      			altRows:true,
      			altClass:'wmsAltRow',
      			loadui: 'block',
      			multiselect: gridMultiSelect > 0,
      			multiselectWidth: 25,      			
				onSelectRow: function(id) {
					/*if ( id && id !== lastsel ) { 
						jQuery('#wms-grid').restoreRow(lastsel); 
						jQuery('#sortrows').editRow(id, true); 
						lastsel = id; 
					 	
						jQuery('#rowed3').jqGrid('restoreRow',lastsel);
						jQuery('#rowed3').jqGrid('editRow',id,true);
					 	
					}*/
				}, 
 				/*ondblClickRow: function(id) { 
					if ( id && id !== lastsel ) { 
						jQuery('#wms-grid').restoreRow(lastsel); 
						jQuery('#wms-grid').editRow(id, true); 
						lastsel = id; 
						
						jQuery('#rowed3').jqGrid('restoreRow',lastsel);
						jQuery('#rowed3').jqGrid('editRow',id,true);
						
					} 
				}, */
				editurl: editUrl,     			
      			onSelectAll: selectAllHandler,
      			gridComplete: gridLoadInit1,                        			
      			loadComplete: function() {
      				emp.$('td.isActive input[type="checkbox"]').each(function() {
      		   			emp.$(this).click(function() {
      		   				var rowId = emp.$(this.parentNode.parentElement).attr('id');
      		   				// console.log("editing row: " + rowId);
      		   				toggleIsActive(rowId);      		   				      		   				
      		   			});
      		   		});
      			},
      			jsonReader : {
      				root: "rows",
      				page: "page",
      				total: "total",
      				records: "records",
      				repeatitems: false,
      				cell: "cell",
      				id: "id"      				
      			}      			
      		}).jqGrid('sortableRows', {
				update: function(event, ui) {
					updateOrder(event, ui, this.rows);
				},
				stop: function(event, ui) {
					// alert('stop');
				}
			});               
      		
      		emp.$('#wms-grid').setGridWidth('auto', true);

       		
/*       		jQuery('#wms-grid tbody').sortable( {
				update: function(event, ui) {
					updateOrder(event, ui, this.rows);
				},
				stop: function(event, ui) {
					//alert('stop');
				}
			});		*/
       		
       		emp.$('#connectionBtn').button().click(function() {  
      			emp.$("#wms-grid").trigger("reloadGrid", [{page:1}]);     			      			
      		});                                     
      		
      		emp.$("#wms-grid").jqGrid('navGrid','#pager1', {refresh:false,edit:false, add:false, del:false, search:false},
      				{}, {}, {}, { 	// search      					
      					sopt:['cn', 'eq', 'ne', 'lt', 'gt', 'bw', 'ew'],
      					closeOnEscape: true,      					
      					multipleSearch: true,
      					closeAfterSearch: true                    					
      				}      				
      		);               
      		
      		emp.$("#wms-grid").jqGrid('gridResize',{minWidth: 300, minHeight: 250});
      		
       		emp.$("#wms-grid").navButtonAdd('#pager1', { 	
      			caption:"",      
      			title: "Reload records",
      			buttonicon:"ui-icon-refresh",
      			onClickButton: reloadMapToolGrid,
      			position: "first",
      			cursor: "pointer"      			
      		});      

      		emp.$("#wms-grid").navButtonAdd('#pager1', { 	
      			caption:"",        
      			title: "Add a record", 			
      			buttonicon:"ui-icon-plus",
      			onClickButton: addRow,
      			position: "last",
      			cursor: "pointer"      			
      		});	
      		
      		emp.$("#wms-grid").navButtonAdd('#pager1', { 	
      			caption:"",   
      			title: "Edit a record",
      			buttonicon:"ui-icon-pencil",
      			onClickButton: editRow,                   
      			position: "last",
      			cursor: "pointer"      			
      		});	
      		
      		emp.$("#wms-grid").navButtonAdd('#pager1', { 	
      			caption:"",   
      			title: "Delete a record",
      			buttonicon:"ui-icon-trash",
      			onClickButton: deleteRow, 
      			position: "last",
      			cursor: "pointer"      			
      		});
      	});          
      	

      	
      	function updateOrder(ev, ui, rows) { 
			var item = ui.item[0];
			var ri = item.rowIndex;
			var id = item.id;
			var msg = "The row with the id=" + id + " has moved. The new row index is " + ri;
			
			if (ri > 1 && ri < rows.length - 1) {
				console.log( msg + "\nTHe row is inserted between item with rowid = " 
						+ rows[ri-1].id + " and the item with the rowid = " 
						+ rows[ri+1].id);
			} else if (ri > 1) {
				console.log(msg + "\nThe row is inserted as the last item after the item with rowid" + rows[ri-1].id);
			} else {
				console.log(msg);
			}
			
			var maps = {};
			jQuery(rows).each(function(index, value) {
				maps[value.id] = value.rowIndex;
			});					

  			jQuery.ajax({
  				url: reorderUrl,
	  			type:"POST",
	  			data: maps,
	  			dataType: "json",
	  			success: function(response) {
	  				if (response.status == "Success") {		  				
		  				jQuery('#msgbox').text('Update success!');
	  		    		jQuery('#msgbox').dialog({
	  		    			title: 'Success',
	  		    			modal: true,
	  		    			buttons: {
	  		    				"Ok": function() {
	  		    					jQuery(this).dialog("close");  		    						  		    					
	  		    				}
	  		    			}     			
	  		    		});    			  
	  				} else {
	  					jQuery('#msgbox').text('Update failed!');
	  		    		jQuery('#msgbox').dialog({
	  		    			title: 'Error',
	  		    			modal: true,
	  		    			buttons: {
	  		    				"Ok": function() {
	  		    					jQuery(this).dialog("close");  		    						  		    					
	  		    				}
	  		    			}     			
	  		    		});    			  		    		
	  				}	  				
	  			},
	  			async:false	  			
  			});
		};      	      	
      	
      	function addRow() {
      		emp.$("#wms-grid").jqGrid('setColProp', 'urlId', {editrules:{required:false}} );
 		
      		// Get the currently selected row 
      		emp.$('#wms-grid').jqGrid('editGridRow','new', { 	
      			url: addUrl,
      			editData: {},
      			width:'auto',
      			serializeEditData: function(data) {    
      				data.id = 0;
      				data.urlId = 0;
      				return emp.$.param(data);                        				
      			},                   
      			recreateForm: true,
      			beforeShowForm: function(form) {
      				emp.$('#pData').hide(); 
      				emp.$('#nData').hide();			
      			},
      			beforeInitData: function(form) {},
      			beforeCheckValues: function(postdata,formid,mode) {
      				emp.$("#wms-grid").jqGrid('setColProp', 'urlId', {editrules:{required:false}}, {editable:false} );      				
      			},
      			closeAfterAdd: true,
      			reloadAfterSubmit:true,
      			afterSubmit : function(response, postdata) {
      				var result = eval('(' + response.responseText + ')');
      				var errors = "";					
      				
      				if (result.success == false) {
      					for (var i = 0; i < result.message.length; i++) {
      						errors +=  result.message[i] + "<br/>";      						
      					}      					
      				}  else {
      					emp.$('#msgbox').text('Entry has been added successfully');
      					emp.$('#msgbox').dialog( {	
      						title: 'Success',
      						modal: true,
      						buttons: {
      							"Ok": function()  {
      								emp.$(this).dialog("close");    							      								
      							}      					
      						}      					
      					});      					
      				}
      				// only used for adding new records
      				var newId = null;
      				//force reloading
      				emp.$("#wms-grid").trigger("reloadGrid");	    	
      				return [result.success, errors, newId];      				
      			}      			
      		});		      		
      	} // end of addRow 
      	
      	function toggleIsActive(rowId) {
	      	if (rowId) {
	  			var row = emp.$('#wms-grid').jqGrid('getRowData', rowId);
	  			emp.$.ajax({
	  				url: editUrl,
	  				type:"POST",
	  				data: row,
	  				dataType: "text",
	  				global: false,					// disable the ajaxStart/ajaxStop loader
	  				success: function(data) {
	  					var json = emp.$.parseJSON(escapeNewLine(data));
	  					if (json.status == "Success") {	
		  					var rowIdx = emp.$("#wms-grid").getInd(json.result.urlId) - 1;
		  					emp.configManager.config.wmsServerUrls[rowIdx].active = json.result.active;
	  					} else {
	  						emp.$('#msgbox').text('Update failed!');
	  		      			emp.$('#msgbox').dialog({      				
	  		      				title: 'Error',
	  		      				modal: true,
	  		      				buttons: {
	  		      					"Ok": function() {
	  		      						emp.$(this).dialog("close");      						
	  		      					}
	  		      				}      			
	  		      			});      		
	  					}
	  				},
	  				async:false
	  			});	  			
	  			
	      	} else {
	      		emp.$('#msgbox').text('Checkbox has not been selected');
      			emp.$('#msgbox').dialog({      				
      				title: 'Error',
      				modal: true,
      				buttons: {
      					"Ok": function() {
      						emp.$(this).dialog("close");      						
      					}
      				}      			
      			});      		
	  		}
      	};
      	
      	function editRow() {
      		emp.$("#wms-grid").jqGrid('setColProp', 'name', 'serverUrl', 'type', {editoptions:{readonly:false, size:55}});        
     		
      		// Get the currently selected row
      		var row = emp.$('#wms-grid').jqGrid('getGridParam','selrow');      		
     		
      		if( row != null ) {	
      			emp.$('#wms-grid').jqGrid('editGridRow', row, {
      				url: editUrl,
      				editData: {},
      				width:500,
      				recreateForm: true,
      				beforeShowForm: function(form) {
      					emp.$('#pData').hide(); 
      					emp.$('#nData').hide();      					
      				},      				
      				beforeSubmit: function(postdata, formid) {
      					postdata.prevServerUrl = emp.$('#wms-grid').jqGrid('getCell', row, 'serverUrl');
      					return [true, ""];
      				},
      				beforeInitData: function(form) {
      					
      				},
      				closeAfterEdit: true,
      				reloadAfterSubmit:true,
      				afterSubmit : function(response, postdata) {      			
      					var result = eval('(' + response.responseText + ')');
      					var errors = "";					
      					if (result.success == false) {
      						for (var i = 0; i < result.message.length; i++) {
      							errors +=  result.message[i] + "<br/>";      							
      						}      						
      					} else {      						
          					var rowIdx = emp.$("#wms-grid").getInd(postdata.urlId) - 1;
          					emp.configManager.config.wmsServerUrls[rowIdx] = postdata;
      						
      						emp.$('#msgbox').text('Entry has been edited successfully');
      						emp.$('#msgbox').dialog({
      							title: 'Success',
      							modal: true,
      							buttons: {
      								"Ok": function() {
      									emp.$(this).dialog("close");     									      									
      								}                                   						
      							}                                  						      						
      						});                                    						
      					}                                                    
      					
      					// only used for adding new records 
      					var newId = null;
      					//force reloading 
      					emp.$("#wms-grid").trigger("reloadGrid");      					
      					
      					return [result.success, errors, newId];                                                        					
      				}    				      				
      			});    			      			
      		} else {
      			emp.$('#msgbox').text('You must select a record first!');
      			emp.$('#msgbox').dialog({      				
      				title: 'Error',
      				modal: true,
      				buttons: {
      					"Ok": function() {
      						emp.$(this).dialog("close");      						
      					}
      				}      			
      			});      			
      		}      		
      	}
      	
      	function deleteRow() {
      		// Get the currently selected row 
      		var row = emp.$('#wms-grid').jqGrid('getGridParam','selrow');
      		var selRows = emp.$('#wms-grid').jqGrid('getGridParam', 'selarrrow');      		
      		var stringArray = selRows;
      		
      		for (var i = 0; i < selRows.length; i++) {
      			stringArray[i] = emp.$('#wms-grid').jqGrid('getCell', selRows[i], 'urlId');
      		}
      		
      		// A pop-up dialog will appear to confirm the selected action
      		if( row != null )
      			emp.$('#wms-grid').jqGrid( 'delGridRow', row, {
      				url: deleteUrl,      				
      				recreateForm: true,
      				beforeShowForm: function(form) {
      					//Change title
      					emp.$(".delmsg").replaceWith('<span style="white-space: pre;">' + 'Delete selected record?' + '</span>');
      					//hide arrows
      					emp.$('#pData').hide();      					
      					emp.$('#nData').hide();              		         					
      				},      				
      				beforeSubmit: function(postdata, formid) {
      					return [true, ""];
      				},
      				reloadAfterSubmit:true,
      				closeAfterDelete: true,
      				serializeDelData: function (postdata) {
      					var rowdata = emp.$('#wms-grid').getRowData(postdata.id);
      					// append postdata with any information
      					return {id: rowdata.urlId, oper: postdata.oper, serverUrl: stringArray.join(",")};      					
      				},
      				afterSubmit : function(response, postdata) {
      					var result = eval('(' + response.responseText + ')');
      					var errors = "";					
      					
      					if (result.success == false) {
      						for (var i = 0; i < result.message.length; i++) {
      							errors +=  result.message[i] + "<br/>";      							
      						}      						
      					}  else {
      						emp.$('#msgbox').text('Entry has been deleted successfully');
      						emp.$('#msgbox').dialog({	
      							title: 'Success',
      							modal: true,
      							buttons: {
      								"Ok": function() {
      									emp.$(this).dialog("close");      									
      								}      						
      							}      						
      						});      						
      					}                       
      					
      					// only used for adding new records
      					var newId = null;
      					//force reloading
      					emp.$("#wms-grid").trigger("reloadGrid");        	
      					
      					return [result.success, errors, newId];      					
      				}     				      				
      			});      		
      		else {
      			emp.$('#msgbox').text('You must select a record first!');
      			emp.$('#msgbox').dialog({	
      				title: 'Error',
      				modal: true,
      				buttons: {
      					"Ok": function() {
      						emp.$(this).dialog("close");      						
      					}      			
      				}      			
      			});      			
      		}      		
      	}

           
   		/*
   		* FUNCT1ION gridLoadInit1
   		* This method is tied to grid loads, through the gridComplete attribute
   		* Any time the data is refreshed in the grid (page load, paging, manual reset, etc)
   		* then this method is run to set event bindings on any created DOM. We also
   		* use this method to re-'check' any records previously selected.
   		*/   		
   		var gridLoadInit1 = function () {
   			// if the 'selected' array has length 
   			// then loop current records, and 'check' 
   			// those that should be selected 
   			if (selArr.length > 0) {
   				var tmp = emp.$("#wms-grid").jqGrid('getDataIDs');
   				emp.$.each(selArr, function(ind, val){
   					var pos = emp.$.inArray(val, tmp);
   					if (pos > -1) {
   						emp.$("#wms-grid").jqGrid('setSelection',val);   						
   					}
   				});   				
   			}   

   			emp.$('#wms-grid ' + 'tr').removeClass("ui-widget-content");
   			emp.$('#wms-grid ' + 'tr:nth-child(odd)').addClass('wmsAltRow');
   		};
   		
   		/*
   		* FUNCTION gridUnloader
   		* Called from within the populateGrid method, this method is to unbind
   		* any event handlers created during grid load, by the gridLoadInit1 method.
   		*/
   		var gridUnloader = function () {   			
   		};
   		
   		/*
   		* FUNCTION selectionManager
   		* Used to handle selections across paging requests
   		*/
   		var selectionManager = function (id, status) {
   			// was it checked (true) or unchecked (false)
   			if(status) {
   				// if it's just one id (not array)
   				if(!emp.$.isArray(id)) {
   					// if it's not already in the array, then add it
   					if (emp.$.inArray(id, selArr) < 0) {
   						selArr.push(id);   						
   					}   					
   				} else {
   					// which id's aren't already in the 'selected' array
   					var tmp = emp.$.grep(id, function(item,ind){
   						return emp.$.inArray(item, selArr) < 0;   						
   					});
   					// add only those unique id's to the 'selected' array
   					emp.$.merge(selArr, tmp);   					
   				}   				
   			} else {
   				// if it's just one id (not array)
   				if(!emp.$.isArray(id)){
   					// remove that one id
   					selArr.splice(emp.$.inArray(id, selArr), 1);   					
   				} else {
   					// give me an array without the 'id's passed
   					// (resetting the 'selected' array)
   					selArr = emp.$.grep(selArr, function(item, ind){
   						return emp.$.inArray(item, id) > -1;   						
   					}, true);   					
   				}   				
   			}		
   		};
   		
   		/*
   		* FUNCTION rowSelectionHandler
   		* Used to handle row selections
   		*/
   		var rowSelectionHandler = function (id, status) {
   			selectionManager(id, status);  			
   		};
   		
   		/*
   		* FUNCTION selectAllHandler
   		* Used to handle selection of all records displayed
   		*/
   		var selectAllHandler = function (idArr, status) {   			
   			selectionManager(idArr, status);   			
   		}; 		   			
   		
